<template>
  <div>
    用户头像修改
    <el-upload
      class="avatar-uploader"
      action="http://localhost:8889/mallUser/update/userImg"
      :show-file-list="true"
      :on-success="handleAvatarSuccess"
      :on-change="checkfile"
      :auto-upload="false"
      :limit="1"
      ref="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

    <el-button type="primary" @click="updateImg">上传图片</el-button>
  </div>
</template>

<script>
import { updateUserImg } from "../api/requestapi";
export default {
  name: "UserImgUpdate",

  data() {
    return {
      imageUrl: "",
      file: {},
      filetype: ["image/jpeg", "image/png", "image/jpg"],
    };
  },

  methods: {
    updateImg() {
      let formdata = new FormData();
      formdata.append("file", this.file);

      updateUserImg(formdata).then((response) => {
        console.log("上传成功了");
        //更新vuex的数据
        this.$store.commit("setUserImgUrl", response.data);
      });
    },

    //上传前检验文件类型 大小
    checkfile(file, filelist) {
      //判断文件大小
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message("文件超过2m了");
        return;
      }
      //判断是否符合类型
      for (var type of this.filetype) {
        if (file.raw.type === type) {
          //清空文件列表
          this.$refs.upload.clearFiles();
          //raw才是文件主体
          this.file = file.raw;
          //暂时显示 文件url
          this.imageUrl = URL.createObjectURL(file.raw);

          return;
        }
      }

      this.$message("文件类型不对");
    },

    //成功之后 更新vuex图片
    handleAvatarSuccess() {},
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>